package org.cocos2dx.javascript.Mob;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.mob.MobSDK;
import com.mob.secverify.SecVerify;
import com.mob.secverify.ui.AgreementPage;
import com.pelbs.book99998.R;

import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import cn.smssdk.SMSSDK;

public class OtherPhoneDialog extends Dialog implements SMSBroadcastReceiver.ISMSListener  {
    private SMSBroadcastReceiver smsReceiver;
    private Button sureButton;
    private Button verifyButton;
    private TextView editPhoneNumber;
    private TextView editVerifyNumber;
    private Context context;
    private String url;
    private  Timer timer = null;
    private int timerCount = 0;

    public OtherPhoneDialog(Context context) {
        super(context, R.style.other_telphone_login);
        this.context = context;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LayoutInflater inflater = LayoutInflater.from(this.context);
        View view = inflater.inflate(R.layout.other_telphone_login, null);
        setContentView(view);
        this.initViewEvent();
    }

    @Override
    protected void  onStart(){
        super.onStart();
        smsReceiver = new SMSBroadcastReceiver(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
        context.registerReceiver(smsReceiver, filter);
        Log.e("onStart", "ndroid.provider.Telephony.SMS_RECEIVED");
        timerCount = 0;
        ((TextView) findViewById(R.id.textTime)).setText("");
    }

    @Override
    protected void onStop(){
        super.onStop();
        context.unregisterReceiver(smsReceiver);
    }

    @SuppressLint({"WrongViewCast", "ClickableViewAccessibility"})
    private void initViewEvent(){

        this.verifyButton = (Button) findViewById(R.id.other_send_verify_btn);
        this.sureButton = (Button) findViewById(R.id.other_login_btn);
        this.editVerifyNumber = (TextView) findViewById(R.id.other_editVerifyNumber);
        this.editPhoneNumber = (TextView)findViewById(R.id.other_editPhoneNumber);

        TextView tvAgreement = findViewById(R.id.login_use_this_number_privacy2);
        tvAgreement.setText(buildSpanString());
        tvAgreement.setHighlightColor(this.context.getResources().getColor(android.R.color.transparent));
        tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());

        this.verifyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editPhoneNumber.getText().length() == 0){
                    Toast.makeText(context, "电话号码不正确", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!isChinaPhoneLegal(editPhoneNumber.getText().toString())){
                    Toast.makeText(context, "手机号码不正确", Toast.LENGTH_LONG).show();
                    return;
                }

                SMSSDK.getVerificationCode("86", editPhoneNumber.getText().toString());
                verifyButton.setEnabled(false);
                timerCount = 60;
                timer = new Timer();
                editVerifyNumber.requestFocus();
                TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    if (timerCount > 0)
                        timerCount = timerCount - 1;
                    findViewById(R.id.textTime).post(new Runnable() {
                        @Override
                        public void run() {
                            if (timerCount == 0) {
                                verifyButton.setEnabled(true);
                                ((TextView) findViewById(R.id.textTime)).setText("");
                                timer.cancel();
                            } else {
                                ((TextView) findViewById(R.id.textTime)).setText("" + timerCount + "秒后可以重新发送");

                            }
                        }
                    });
                }};
                timer.schedule(timerTask, 0, 1000);
            }
        });

        this.verifyButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        if(v.getId() == R.id.other_send_verify_btn){
                            verifyButton.setScaleX((float)0.95);
                            verifyButton.setScaleY((float)0.95);
                        }
                        break;


                    case MotionEvent.ACTION_UP:
                        if(v.getId() == R.id.other_send_verify_btn){
                            verifyButton.setScaleX(1);
                            verifyButton.setScaleY(1);
                        }
                        break;
                }
                return false;
            }

        });

        findViewById(R.id.login_question_btn2).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
               //QuestionDialog dlg = new QuestionDialog(context);
               // dlg.show();

                SecVerify.finishOAuthPage();
            }
        });

        this.sureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editVerifyNumber.getText().length() == 0){
                    Toast.makeText(context, "验证码不正确", Toast.LENGTH_SHORT).show();
                    return;
                }

                PhoneLoginMgr.getInstance().specialLogin(editPhoneNumber.getText().toString(), editVerifyNumber.getText().toString());
                SdkSetting.saveSeting(context, "phoneNumber", editPhoneNumber.getText().toString());
                sureButton.setEnabled(false);
            }
        });

        this.sureButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        if(v.getId() == R.id.other_login_btn){
                            sureButton.setScaleX((float)0.95);
                            sureButton.setScaleY((float)0.95);
                        }
                        break;


                    case MotionEvent.ACTION_UP:
                        if(v.getId() == R.id.other_login_btn){
                            sureButton.setScaleX(1);
                            sureButton.setScaleY(1);
                        }
                        break;
                }
                return false;
            }
        });

    }

    public void enableSureButton(){
        sureButton.setEnabled(true);
    }

    private SpannableString buildSpanString() {
        String operatorText = "";
        if (OperatorUtils.getCellularOperatorType() == 1) {
            operatorText = "《中国移动认证服务条款》";
            url = "https://wap.cmpassport.com/resources/html/contract.html";
        } else if (OperatorUtils.getCellularOperatorType() == 2) {
            operatorText = "《中国联通认证服务条款》";
            url = "https://ms.zzx9.cn/html/oauth/protocol2.html";
        } else if (OperatorUtils.getCellularOperatorType() == 3) {
            operatorText = "《中国电信认证服务条款》";
            url = "https://e.189.cn/sdk/agreement/content.do?type=main&appKey=&hidetop=true&returnUrl=";
        }
        String ageementText = "同意" + operatorText + "及《隐私政策》和" +
                "《用户使用协议》并授权秒验使用本机号码登录";
        String cusPrivacy1 = "《隐私政策》";
        String cusPrivacy2 = "《用户使用协议》";
        String cusPrivacy3 = "《其他隐私政策》";
        int baseColor = MobSDK.getContext().getResources().getColor(R.color.sec_verify_demo_text_color_common_black);
        int privacyColor = Color.parseColor("#FFFE7A4E");
        int cusPrivacyColor1 = Color.parseColor("#FF4E96FF");
        int cusPrivacyColor2 = Color.parseColor("#FF4E96FF");
        int cusPrivacyColor3 = Color.parseColor("#FFFE7A4E");
        SpannableString spanStr = new SpannableString(ageementText);
        int privacyIndex = ageementText.indexOf(operatorText);
        spanStr.setSpan(new ForegroundColorSpan(baseColor)
                , 0, ageementText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //设置文字的单击事件
        spanStr.setSpan(new ClickableSpan() {
            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(View widget) {
                gotoAgreementPage(url, "");
            }
        }, privacyIndex, privacyIndex + operatorText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //设置文字的前景色
        spanStr.setSpan(new ForegroundColorSpan(privacyColor), privacyIndex, privacyIndex + operatorText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (!TextUtils.isEmpty(cusPrivacy1)) {
            int privacy1Index = ageementText.indexOf(cusPrivacy1);
            //设置文字的单击事件
            spanStr.setSpan(new ClickableSpan() {
                @Override
                public void updateDrawState(TextPaint ds) {
                    ds.setUnderlineText(false);
                }

                @Override
                public void onClick(View widget) {
                    String appCompany = PhoneLoginMgr.getInstance().getAppCompany();
                    gotoAgreementPage("http://private" + appCompany + ".yfqp.shop/index.html", null);
//					if (wrapper != null && wrapper.cusAgreement1Clicked != null){
//						wrapper.cusAgreement1Clicked.handle();
//					}
                }
            }, privacy1Index, privacy1Index + "《隐私政策》".length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            //设置文字的前景色
            spanStr.setSpan(new ForegroundColorSpan(cusPrivacyColor1), privacy1Index, privacy1Index + cusPrivacy1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if (!TextUtils.isEmpty(cusPrivacy2)) {
            int privacy2Index = ageementText.lastIndexOf(cusPrivacy2);
            //设置文字的单击事件
            spanStr.setSpan(new ClickableSpan() {
                @Override
                public void updateDrawState(TextPaint ds) {
                    ds.setUnderlineText(false);
                }

                @Override
                public void onClick(View widget) {
                    gotoAgreementPage("http://useragree.yfqp.shop/index.html", null);
                }
            }, privacy2Index, privacy2Index + cusPrivacy2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            //设置文字的前景色
            spanStr.setSpan(new ForegroundColorSpan(cusPrivacyColor2), privacy2Index, privacy2Index + cusPrivacy2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        /*
        if (!TextUtils.isEmpty(cusPrivacy3)) {
            int privacy3Index = ageementText.lastIndexOf(cusPrivacy3);
            //设置文字的单击事件
            spanStr.setSpan(new ClickableSpan() {
                @Override
                public void updateDrawState(TextPaint ds) {
                    ds.setUnderlineText(false);
                    ds.linkColor = Color.parseColor("#FFFFFF");
                }

                @Override
                public void onClick(View widget) {
                    Log.e("gotoAgreementPage3", "spanStr gotoAgreementPage3");
                    gotoAgreementPage("https://www.baidu.com", null);
                }
            }, privacy3Index, privacy3Index + cusPrivacy3.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            //设置文字的前景色
            spanStr.setSpan(new ForegroundColorSpan(cusPrivacyColor3), privacy3Index, privacy3Index + cusPrivacy3.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
         */
        return spanStr;
    }

    @Override
    public void dismiss() {
        View view = getCurrentFocus();
        if(view instanceof TextView){
            InputMethodManager mInputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            mInputMethodManager.toggleSoftInputFromWindow(view.getWindowToken(), 0, 0);
        }
        super.dismiss();
    }

    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
        // ^ 匹配输入字符串开始的位置
        // \d 匹配一个或多个数字，其中 \ 要转义，所以是 \\d
        // $ 匹配输入字符串结尾的位置
        String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" +
                "|(18[0-9])|(19[8,9]))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    //可替换为跳转自己的webview
    private static void gotoAgreementPage(String agreementUrl, String title) {
        if (TextUtils.isEmpty(agreementUrl)) {
            Log.e("OtherPhoneDialog", "gotoAgreementPage return");
            return;
        }
        AgreementPage page = new AgreementPage();
        Intent i = new Intent();
        i.putExtra("extra_agreement_url", agreementUrl);
        if (!TextUtils.isEmpty(title)) {
            i.putExtra("privacy", title);
        }
        page.show(MobSDK.getContext(), i);
    }

    @Override
    public void onSmsReceiver(String verifyCode) {
        this.editVerifyNumber.setText(verifyCode);
        Log.e("editVerifyNumber", verifyCode);
    }
}
